package com.iwdnb.gkgz.common.utils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.iwdnb.bmnf.common.utils.HttpClientUtils;
import com.iwdnb.gkgz.common.model.dto.StockDayData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

@Slf4j
public class SinaStockUtils {

    public static List<StockDayData> getHistoryData(String code, Date beginDate, Date endDate) {
        try {
            //新浪股票行情历史接口
            String url = "https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param=%s,day,%s,%s,%s,qfq";
            long date = DateUtil.between(beginDate, endDate, DateUnit.DAY);
            url = String.format(url, code, DateUtil.formatDate(beginDate), DateUtil.formatDate(endDate), date + "");
            String body = HttpClientUtils.get(url);
            JSONObject jsonObject = JSON.parseObject(body);
            if (!jsonObject.getString("code").equals("0")) {
                log.error("getHistoryData response error:" + body);
                return null;
            }
            //log.info("sina stock response:" + body);
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONObject(code).getJSONArray("qfqday");
            if (CollectionUtils.isEmpty(jsonArray)) {
                return null;
            }
            List<StockDayData> stockDayDataList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONArray data = jsonArray.getJSONArray(i);
                StockDayData stockDayData = new StockDayData();
                stockDayData.setCode(code);
                stockDayData.setDate(data.getString(0));
                stockDayData.setOpenPrice(new BigDecimal(data.getString(1)));
                stockDayData.setClosePrice(new BigDecimal(data.getString(2)));
                stockDayData.setMaxPrice(new BigDecimal(data.getString(3)));
                stockDayData.setMinPrice(new BigDecimal(data.getString(4)));
                stockDayData.setTradeNum(data.getBigDecimal(5).intValue());
                stockDayDataList.add(stockDayData);
            }
            return stockDayDataList;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

}
